import openai
from flask import Flask, redirect, url_for, render_template, request
from flask_uuid import FlaskUUID

app = Flask(__name__)

# os.urandom(24)
app.config["SECRET_KEY"] = "wb04307201-chat-gpt"
# 在flask下可以将有效期延长至一个月
# session.permanent = True
# 给app.config设置PERMANENT_SESSION_LIFETIME来更改有效期，这个值的数据类型是datetime.timedelta类型。在登陆网页界面的时候，有个‘记住我’的选项，如果点击了就把session的有效期延长一些，使用的就是这个。前提是要session.permanent=True
# app.config["PERMANENT_SESSION_LIFETIME"] = datetime.timedelta(days=7)

FlaskUUID(app)

# 换成自己的api_key
openai.api_key = ""


@app.route('/')
def reindex():
    return redirect(url_for('index'))


chat_list = {}


@app.route('/index', methods=['POST', 'GET'])
def index():
    # if session.get("name") is None:
    #     session["name"] = str(uuid.uuid4())

    # name = session.get("name")
    # if name not in chat_list.keys():
    #     chat_list[name] = []

    # if request.method == 'POST' and request.form.get("prompt") != "" and request.form.get("prompt") is not None:
    #     me = request.form.get("prompt")
    #     print("me quest:", me)
    #     response = openai.Completion.create(model="text-davinci-003", prompt=me, temperature=0, max_tokens=2048)
    #     chatGPT = response.choices[0].text
    #     print("chatGPT answer:", chatGPT)
    #     chat_list[name].append({"me": me, "chatGPT": chatGPT})
    #     if len(chat_list[name]) > 50:
    #         del chat_list[name][0]

    return render_template('index.html')


@app.route('/chat', methods=['POST'])
def chat():
    request_json = request.get_json()
    messages = request_json.get("messages")
    print("ask:", messages)
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0301",
        messages=messages,
        timeout=60,  # 设置超时响应时间为60秒
    )
    print("answer:", response.choices[0].message['content'])
    return response


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
